package com.hexacta.hrs.repositories.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.hibernate.Criteria;
import org.vectrics.employee.Employee;

import com.hexacta.hrs.domain.exchange.Accrued;
import com.hexacta.hrs.domain.exchange.AccruedReferring;
import com.hexacta.hrs.domain.exchange.Confirmation;
import com.hexacta.hrs.domain.exchange.Currency;
import com.hexacta.hrs.repositories.exchange.AccruedRepository;

public class AccruedRecordObjectRepository extends HibernateRecordObjectRepository<Accrued> implements AccruedRepository{

	public AccruedRecordObjectRepository(Class<Accrued> entityClass) {
		super(entityClass);
	}

	@Override
	public void delete(Accrued entity) {
		super.delete(entity);
	}

	@Override
	public Accrued forId(Long id) {
		return super.forId(id);
	}

	@Override
	public Collection<Accrued> matching(Accrued criteria) {
		return super.matching(criteria);
	}

	@Override
	public void save(Accrued entity) {
		super.save(entity);
	}

	@Override
	public Collection<Accrued> all() {
		return super.all();
	}

	@Override
	public void saveConfirmation(Confirmation confirmation) {
		super.getSession().save(confirmation);
	}

	@Override
	public List<Accrued> byProject(Long selectedProjectId) {
		Criteria crit = getSession().createCriteria(Accrued.class);
		return null;
	}

	@Override
	public List<AccruedReferring> byReferring(Employee partner, Integer year, Integer month) {
		String query = "SELECT ac, p.name, p.currency "+
						" FROM Project AS p JOIN p.accrueds AS ac JOIN p.referrings AS ref "+
						"WHERE ref.partner.id = "+partner.getId()+ " AND ac.year = "+year+" AND ac.month = "+month;
		
		List<Object> objectResult = getSession().createQuery(query).list(); 
		List<AccruedReferring> accruedReferrings = new ArrayList<AccruedReferring>();
		
		
		 Transformer transformer = new Transformer() {
	            @Override
	            public Object transform(final Object input) {
	            	Object[] accruedReferring = (Object[]) input;
	            	Accrued accrued = (Accrued) accruedReferring[0];
	            	String name = (String) accruedReferring[1];
	            	Currency currency = (Currency) accruedReferring[2];
	            	
	            	return new AccruedReferring(accrued, name, currency);
	            }
		 };
		 
		 CollectionUtils.collect(objectResult, transformer, accruedReferrings);
		 
		return accruedReferrings;
	}
	
}
